
$(document).ready(function() {
	var isToShowSummary = false;
	
	$(".icon-wrp").click(function() {
		var eleId = $(this).attr("for");
		if (eleId)
			$("#" + eleId).focus();
	});
	
	// Events handler for left navigation menu clicks
	$(".leftNav li a").click(function() {
		var divNm = $(this).attr('rel');
		$(".leftNav li a").removeClass('active');
	    $(this).addClass('active');
		$(".formDiv").css({position:"absolute",left:"-9999px",top:"-9999px"});
		$("." + divNm).css("position","static");
		if (divNm === 'manageract') {
			$("#myTable").live().jqTransform({
				imgPath : 'images/'
			});
		}
	});
	
	// Events handler for left navigation menu clicks
	$("li.menuItem a").click(function() {
		var divNm = $(this).attr('rel');
		$(".leftNav li a").removeClass('active');
	    $(this).addClass('active');
		$(".formDiv").css({position:"absolute",left:"-9999px",top:"-9999px"});
		$("." + divNm).css("position","static");
		// $(".rightNav").load('pages/reimbursement.jsp');
		if (divNm === 'manageract') {
			$("#myTable").live().jqTransform({
				imgPath : 'images/'
			});
		}
	});

	// Submitting for generating Time Sheet
	$("#timeSheetBtn").click(function () {
		var fromDate = new Date($("#from").val());
		var toDate =  new Date($("#to").val());
		if (fromDate > toDate) {
			notifierInst.showMessage("Error::Invalid dates. From date cannot be greater than To date");
		} else 
		if ($("#from").val() == "" || $("#to").val() == "" || $("#fromHrs").val() == "" || $("#toHrs").val() == "") {
			notifierInst.showMessage("Error::Please select valid dates & work hours");
		} else {
			document.forms["timesheet"].submit();
		}
	});
	
	
	// Submitting for generating the Reimbursement Forms
	$("#reimburseBtn").click(function () {
		if ($("#month").val() != 0 && $("#formtype").val() != 0) {
			document.forms["reimburse"].submit();
		} else {
			notifierInst.showMessage("Error::Please select both Month and Form Type");
		}
	});
	
	// Handler for CheckAll checkbox in Managerial Activities
	$("#checkAll").click(function () {
	
		var c = $("#tbody .jqTransformCheckbox");
		var xx = !$('#headerRow .jqTransformCheckbox').is('.jqTransformChecked');
		$.each(c, function (index, item) {
			if (!$(item).next().attr('disabled')) {
				$(item).next().attr('checked', xx);
				$(item).toggleClass('jqTransformChecked', xx);
			}
		});
	});
	
	$( '.cb-element' ).live( 'change', function() {
		var chked = $( '.cb-element:checked' ).length;
		var elems = $( '.cb-element' ).length;
		elems == chked ? $( '#checkAll' ).attr( 'checked', 'checked' ) : $( '#checkAll' ).attr( 'checked', false );
		if (elems === chked) {
			$('#headerRow .jqTransformCheckbox').addClass('jqTransformChecked');
		}else{
			$('#headerRow .jqTransformCheckbox').removeClass('jqTransformChecked');
		}
	});
	
	$('#groupExec').click(function() {
		
		var c = $("#tbody .jqTransformCheckbox.jqTransformChecked"), isToSubmit = true, errMsg="";
		if (c.length <= 0) {
			errMsg = "Please select at least one user.";
			isToSubmit = false;
		}
		$.each(c, function(index, item) {
			var name = $(item).next().attr('name');
			var selIndex = name.substr(name.lastIndexOf('_') + 1);
			
			var x = parseInt($('#selectedMonth'+selIndex).val());
			if(x < 0 && isToSubmit) {
				errMsg = "Please select month for "+$("#name"+selIndex).text();
				isToSubmit = false;
				return;
			}		
		});
		
		if (isToSubmit) {
			var form = $('#manact');
			form.submit();
		} else {
			notifierInst.showMessage('Error::' + errMsg);
		}
			
	});
	$('#genSummary').click(function() {
		var c = $("#tbody .jqTransformChecked"), isToSubmit = true, errMsg="";
		if (c.length <= 0) {
			errMsg = "Please select at least one user.";
			isToSubmit = false;
		}
		if (isToSubmit && $("#target").val() === '') {
			errMsg = "Please select target folder";
			isToSubmit = false;
		}
		if (isToSubmit) {
			var form = $('#manact');
			$.post(
				"ttgroupExec",
				{action: 'generateSummary', data: form.serialize()},
				function(data) {
					notifierInst.showMessage('Reports successfully generated.');
				}
			);	
		} else {
			notifierInst.showMessage("Error::"+errMsg);
		}
	});
	
	$('#showSumry').click(function (){
		isToShowSummary = !isToShowSummary;
		var text = (isToShowSummary === true) ? 'Hide Summary' : 'Show Summary';
		$('#showSumry span span').text(text);
		$("#sumryTbl").toggle("blind");
	});
	
	$('#addBill').click(function() {
		if($('#billNo').val() === '') {
			notifierInst.showMessage("Error::Bill No. is required");
		} else if($('#billDate').val() === '') {
			notifierInst.showMessage("Error::Bill Date is required");
		} else if($('#drName').val() === '') {
			notifierInst.showMessage("Error::Doctor name is required");
		} else if($('#amount').val() === '') {
			notifierInst.showMessage("Error::Amount is required");
		} else if($('#patName').val() === '') {
			notifierInst.showMessage("Error::Patient name is required");
		} else {
			document.forms["addMedical"].submit();
		}
	});
	
	$('#exportBills').click(function () {
		var action = document.forms["addMedical"].action;
		action = action + "?action=exportBills";
		document.forms["addMedical"].action = action;
		document.forms["addMedical"].submit();
	});
	
	$('#addUserBtn').click(function () {
		var isToSubmit = true;
		if ($("#empName").val() === '') {
			notifierInst.showMessage("Error::User Name is required.");
			isToSubmit = false;
		} else if ($("#manager").val() === '') {
			notifierInst.showMessage("Error::Manager Name is required.");
			isToSubmit = false;
		}
		if (isToSubmit) {
			document.forms["addUser"].submit();
		}
	});
	
	$('#addHoliday').click(function () {
		var isToSubmit = true;
		if ($('#holiday').val() == '') {
			notifierInst.showMessage("Error::Please enter holiday date.");
			isToSubmit = false;
		} else if ($('#desc').val() == '') {
			notifierInst.showMessage("Error::Description is required.");
			isToSubmit = false;
		}
		if (isToSubmit) {
			document.forms["addHoliday"].submit();
		}
	});
	
	$('#autoGenChkBox').click(function(event) {
		var ss= $('#reimburse .jqTransformCheckbox').is('.jqTransformChecked');
		if (!ss) {
			var xx = confirm('You have chosen reports to be auto generated.\n On 25th of every month, the report will be generated');
			if (xx) {
				$("#month").attr("disabled", true);
				$("#formtype").attr("disabled", true);
				$("#reimburseBtn").attr("disabled", true);
				$("#reimburse .jqTransformSelectWrapper").css({'color': '#ccc'});				
			} else { event.preventDefault();}
		} else {
			$("#month").removeAttr("disabled");
			$("#formtype").removeAttr("disabled");
			$("#reimburseBtn").removeAttr("disabled");
			$("#reimburse .jqTransformSelectWrapper").css({'color': '#000'});
		}
	});
	
	$('.title').click(function() {
		$("#"+this.id + "1").toggle("blind");
	});
	
	$('#leaveApply').click(function() {
		var errorCode;
		
		errorCode = validateDates($("#leavefrom").val(), $("#leaveto").val(), 'From Date' , 'To Date', true);
				
		if (errorCode) {
			notifierInst.showError(errorCode);
		} else if($('#reason').val() === '') {
			notifierInst.showError("Reason is required");
		} else {
			$('#leavepage').submit();
		}				
	});
	
	$("#showLeaveHolidayCalendar").click(function () {
	    if (!fccInst) {
		fccInst = new FCController();
	    
	    var calendar = $('#calendar').fullCalendar({
	        theme: true,
	        header: {
	            right: 'prev,next today',
	            left: 'title'
	           // right: 'month,agendaWeek,agendaDay'
	        },
	        dayClick: function(date, allDay, jsEvent, view) {
	            fccInst.onDayClick(date, allDay, jsEvent, view);
	        },
	        viewDisplay: function(view) {
	            fccInst.onViewChange(view);
	        },
	        events:getEvents()
	    });

	    fccInst.render(calendar);
	    
	    $.post(
	    		"ttgetDataServlet",
	    		{action: 'leaves'},
	    		function(data) {
	    			fccInst.loadLeaves(data);
	    		}
	    );
	    } else {
	    	$('#calendar').toggle();
	    }
	});
	
	  $("#myTable tr.odd td").click(function(){
          $(this).next("tr").toggle();
          $(this).find(".arrow").toggleClass("up");
      });
	  
	  $("#workHrsPerDay").change(function(){
		 var hrs = this.value;
		 calculateWorkTime(hrs);
				 
	  });
	  
	  $("#genShiftStart").change(function() {
		  var hrs = $("#workHrsPerDay").val();
		  calculateWorkTime(hrs);
	  });
	  
	  function calculateWorkTime(hrs) {
		  var x = $("#genShiftStart").val(),
		  time = x.split(":");
		  if (time[0].indexOf("0") == 0){
			  time[0] = time[0].substr(1);
		  }
		  var y = parseInt(time[0]) + parseInt(hrs);
		  $("#genShiftEnd").attr('value', y+":"+time[1]);
	  }
		
});
